<template>
  <el-card shadow="hover" >
    <el-form label-width="100px" inline :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select v-model="category1Id">
          <el-option
            v-for="c1 in category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="category2Id">
          <el-option
            v-for="c2 in category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select v-model="category3Id">
          <el-option
            v-for="c3 in category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapActions, mapState, mapMutations } from "vuex";
export default {
  name: "Category",
  data() {
    return {
      category1Id: undefined,
      category2Id: undefined,
      category3Id: undefined,
    };
  },
  props:['disabled'],
  mounted() {
    this.getCategory1List();
  },
  // 组件卸载之前，重置整个vuex数据
  beforeDestroy(){
    this.RESET_STATE()
  },
  methods: {
    ...mapActions("category", [
      "getCategory1List",
      "getCategory2List",
      "getCategory3List",
    ]),
    ...mapMutations("category", [
      "UPDATE_CATEGORY3ID",
      "RESET_CATEGORY2LIST",
      "RESET_CATEGORY3LIST",
      "RESET_STATE",
    ]),
  },
  computed: {
    ...mapState("category", [
      "category1List",
      "category2List",
      "category3List",
    ]),
  },
  watch: {
    // 当选中以一级类时，更新/重置 二级分类列表
    category1Id() {
      this.RESET_CATEGORY2LIST();
      this.RESET_CATEGORY3LIST();
      this.category2Id = undefined;
      this.category3Id = undefined;
      this.getCategory2List(this.category1Id);
    },
    // 当选中二级分类时，更新/重置 三级分类列表
    category2Id() {
      if (!this.category2Id) return;
      this.RESET_CATEGORY3LIST();
      this.category3Id = undefined;
      this.getCategory3List(this.category2Id);
    },
    // 当选中三级分类时
    category3Id: {
      handler(newCategory3Id) {
        // if (!newCategory3Id) {
        //   this.$bus.$emit("clearSpuList");
        //   return;
        // }
        this.UPDATE_CATEGORY3ID(newCategory3Id);
        // this.$bus.$emit("getSpuList");
      },
    },
  },
};
</script>

<style scoped>
.el-form--inline {
  margin-bottom: -20px;
}
</style>
